/*
 * @Author: Devin
 * @Date: 2022-04-22 14:43:37
 * @LastEditors: Devin
 * @LastEditTime: 2022-04-27 18:13:01
 */
import { ElLoading } from '@/components/loading';
import _ from 'lodash';
import { h } from 'vue';
let requestObj: any = {};
let needLoadingRequestCount: number = 0;
let loading: any = null;
let timer: NodeJS.Timeout;

const startLoading = () => {
  timer ? clearTimeout(timer) : '';
  loading = ElLoading.service({
    fullscreen: true,
    text: '加载中',
    background: 'rgba(0, 0, 0, 0.7)',
    render: () =>
      h('div', { class: 'cc-loading-container' }, [
        h('div', { class: 'cc-loading-first' }),
        h('div', { class: 'cc-loading-ball' }),
        h('div', { class: 'cc-loading-ball' }),
        h('div', { class: 'cc-loading-ball' }),
        h('div', { class: 'cc-loading-ball' }),
        h('div', { class: 'cc-loading-ball' }),
        h('div', { class: 'cc-loading-ball' }),
        h('div', { class: 'cc-loading-ball' })
      ]),
    customClass: 'cc-loading'
  });
};

export const endLoading = () => {
  loading.close();
};

const tryCloseLoading = () => {
  if (needLoadingRequestCount === 0) {
    endLoading();
    requestObj = {};
  }
};

export const showFullScreenLoading = () => {
  if (needLoadingRequestCount === 0) {
    startLoading();
    requestObj = {};
  }
  needLoadingRequestCount++;
  requestObj[needLoadingRequestCount] = {
    startTime: new Date().valueOf(),
    endTime: ''
  };
};

export const tryHideFullScreenLoading = () => {
  if (needLoadingRequestCount <= 0) {
    requestObj = {};
    return;
  }
  // 只剩最后一个请求
  if (needLoadingRequestCount === 1) {
    requestObj[needLoadingRequestCount].endTime = new Date().valueOf();
  } else {
    requestObj[needLoadingRequestCount] = null;
    delete requestObj[needLoadingRequestCount];
  }
  needLoadingRequestCount--;
  if (needLoadingRequestCount === 0) {
    const timeRange = requestObj['1'].endTime - requestObj['1'].startTime;
    requestObj = {};
    // 防止时间短闪烁
    if (timeRange < 300) {
      timer ? clearTimeout(timer) : '';
      timer = setTimeout(() => {
        tryCloseLoading();
        clearTimeout(timer);
      }, 300);
    } else {
      //创建一个 debounced（防抖动）函数，该函数会从上一次被调用后，延迟 wait 毫秒后调用 func 方法
      _.debounce(tryCloseLoading, 300)();
    }
  }
};
